package io.itit.ecp.admin.server.service.impl;

import com.alibaba.fastjson.JSON;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.itit.ecp.admin.common.enums.IMeterDeviceEnums;
import io.itit.ecp.admin.server.entity.*;
import io.itit.ecp.admin.server.mapper.SceneEdificeMapper;
import io.itit.ecp.admin.server.service.*;
import io.itit.grass.common.exception.GrassException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：楼栋服务实现类
 * @Date：Create by 2023-11-23 09:55:22
 */
@Service
public class SceneEdificeServiceImpl extends JoinServiceImpl<SceneEdificeMapper, SceneEdificeEntity> implements ISceneEdificeService {

    @Resource
    private ISceneFloorService sceneFloorService;

    @Resource
    private ISceneRoomService sceneRoomService;

    @Resource
    private IMeterDeviceService meterDeviceService;
    @Resource
    private IDeviceService deviceService;
    @Resource
    private IEarlyWarningService earlyWarningService;
    @Resource
    private IEnergyDataService energyDataService;
//    @Resource
//    private ISceneRoomService sceneRoomService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveEdifice(SceneEdificeEntity entity, String floorJson) {
        this.save(entity);
        // 保存楼层信息
        List<SceneFloorEntity> floors = JSON.parseArray(floorJson, SceneFloorEntity.class);
        floors.forEach(sceneFloorEntity -> sceneFloorEntity.setSceneProjectId(entity.getSceneProjectId()));
        floors.forEach(sceneFloorEntity -> sceneFloorEntity.setSceneEdificeId(entity.getId()));
        return sceneFloorService.saveBatch(floors);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEdifice(SceneEdificeEntity entity, String floorJson) {
        this.updateById(entity);
        return sceneFloorService.saveEdificeFloors(entity.getId(), entity.getSceneProjectId(), floorJson);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveEdificeBatch(List<SceneEdificeEntity> entities) {
        boolean res = this.saveBatch(entities);
        entities.forEach(edifice -> sceneFloorService.initFloorByEdifice(edifice));
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeEdifices(List<String> ids) {
        // 查询关联的楼层 楼层没法取消关联，直接删
//        long countFloor = sceneFloorService.lambdaQuery()
//                .select(SceneFloorEntity::getId)
//                .in(SceneFloorEntity::getSceneEdificeId,ids)
//                .count();
//        GrassException.throwEx(countFloor > 0,"项目已被楼层模块关联，请在解绑后重试！");

        // 查询关联的空间
        long countRoom = sceneRoomService.lambdaQuery()
                .select(SceneRoomEntity::getId)
                .in(SceneRoomEntity::getSceneEdificeId, ids)
                .count();
        GrassException.throwEx(countRoom > 0, "项目已被空间模块关联，请在解绑后重试！");

        // 查询关联的计量设备
        long countMdevice = meterDeviceService.lambdaQuery()
                .select(MeterDeviceEntity::getId)
                .in(MeterDeviceEntity::getSceneEdificeId, ids)
                .eq(MeterDeviceEntity::getDelFlag, IMeterDeviceEnums.DelFlag.delFlag1.delFlag)
                .count();
        GrassException.throwEx(countMdevice > 0, "项目已被计量设备模块关联，请在解绑后重试！");

        // 查询关联的设备
        long countDevice = deviceService.lambdaQuery()
                .select(DeviceEntity::getId)
                .in(DeviceEntity::getSceneEdificeId, ids)
                .count();
        GrassException.throwEx(countDevice > 0, "项目已被设备模块关联，请在解绑后重试！");

        // 查询关联的预警设置
        long countEarlyWarning = earlyWarningService.lambdaQuery()
                .select(EarlyWarningEntity::getId)
                .in(EarlyWarningEntity::getSceneEdificeId, ids)
                .count();
        GrassException.throwEx(countEarlyWarning > 0, "项目已被预警设置模块关联，请在解绑后重试！");


        // 查询关联的能源数据.
        long countEnergyData = energyDataService.lambdaQuery()
                .select(EnergyDataEntity::getId)
                .in(EnergyDataEntity::getSceneEdificeId, ids)
                .count();
        GrassException.throwEx(countEnergyData > 0, "项目已被能源数据模块关联，请在解绑后重试！");

        // 把楼层删了
        sceneFloorService.lambdaUpdate().in(SceneFloorEntity::getSceneEdificeId, ids).remove();

        return this.removeBatchByIds(ids, 1000);
//        List<SceneFloorEntity> floors = sceneFloorService.lambdaQuery()
//                .select(SceneFloorEntity::getId)
//                .in(SceneFloorEntity::getSceneEdificeId, ids)
//                .list();
//        if (!floors.isEmpty()){
//            List<String> floorIds = floors.stream().map(SceneFloorEntity::getId).collect(Collectors.toList());
//            sceneFloorService.removeFloors(floorIds);
//        }
//        // 删除楼栋
//        return this.removeBatchByIds(ids, 1000);
    }

    @Override
    public String getSceneInfoName(String edificeId, String floorId, String roomId) {
        String name = "";
        if (edificeId != null) {
            // 查询楼栋名称
            SceneEdificeEntity edifice = this.lambdaQuery()
                    .select(SceneEdificeEntity::getEdificeName)
                    .eq(SceneEdificeEntity::getId, edificeId)
                    .one();
            if (edifice == null) {
                return "";
            }
            name = edifice.getEdificeName();
            if (floorId != null) {
                // 查询楼层名称
                SceneFloorEntity floor = sceneFloorService.lambdaQuery()
                        .select(SceneFloorEntity::getFloorName)
                        .eq(SceneFloorEntity::getId, floorId)
                        .one();
                name += "-" + floor.getFloorName();
                if (roomId != null) {
                    // 查询空间名称
                    SceneRoomEntity room = sceneRoomService.lambdaQuery()
                            .select(SceneRoomEntity::getRoomName)
                            .eq(SceneRoomEntity::getId, roomId)
                            .one();
                    name += "-" + room.getRoomName();
                }
            }
        }
        return name;
    }
}
